// content.js

const domKey = "article-viewer markdown-body result"
let backData;

console.log("内容脚本已加载");
document.addEventListener('keydown', (event) => {
  //
  const onChangePage = (addPage) => {
    //内容脚本给后台脚本发送消息
    chrome.runtime.sendMessage({ action: "fetchData", addPage })
      .then(response => {
        const { data, status } = response
        if (status === 'success') {
          changeContent(`${data.title}     

        ${data.detail}`, domKey);

        }
      })
      .catch(error => console.error("通信失败：", error));
  }

  // 示例：监听 Ctrl + S 组合键
  if (event.key === 'ArrowRight') {
    event.preventDefault(); // 阻止默认保存行为
    console.log('下一页')
    onChangePage(1)

  } else if (event.key === 'ArrowLeft') {
    event.preventDefault(); // 阻止默认保存行为
    console.log('上一页！');
    onChangePage(-1)
  } else if (event.key === ' ') {
    event.preventDefault(); // 阻止默认保存行为
    console.log('显示最新章节');
    if (backData) {
      getDom(domKey).innerHTML = backData
      backData = undefined
    } else {
      backData = getDom(domKey).innerHTML
      onChangePage(0)
    }

  } else if (event.key === 'ArrowDown') {
    if (backData) {
      //阅读状态下翻页
      scrollView(true);
      event.preventDefault();
    
    }

  }else if (event.key === 'ArrowUp') {
    if (backData) {
      //阅读状态下翻页
      scrollView(false);
      event.preventDefault();
    
    }

  }
});


/**
 * 后台给内容组件发送消息
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "triggerFunction") {
    console.log("收到指令：", message);
    // 执行自定义方法
    const content = message.data
    changeContent(`${content.title}      

     ${content.detail}`, domKey);
    sendResponse({ status: "执行成功" });  // 可选响应
  }
  return true;  // 保持异步响应通道
});

function getDom(_id) {
  return _id.includes('#') ? document.getElementById(_id.slice(1)) : document.getElementsByClassName(_id)[0];
}

async function changeContent(_text, _id = '#aaa') {
  const styleStr = `<style>.markdown-body{word-break:break-word;line-height:1.75;font-weight:400;font-size:16px;overflow-x:hidden;color:#252933}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{line-height:1.5;margin-top:35px;margin-bottom:10px;padding-bottom:5px}.markdown-body h1{font-size:24px;line-height:38px;margin-bottom:5px}.markdown-body h2{font-size:22px;line-height:34px;padding-bottom:12px;border-bottom:1px solid #ececec}.markdown-body h3{font-size:20px;line-height:28px}.markdown-body h4{font-size:18px;line-height:26px}.markdown-body h5{font-size:17px;line-height:24px}.markdown-body h6{font-size:16px;line-height:24px}.markdown-body p{line-height:inherit;margin-top:22px;margin-bottom:22px}.markdown-body img{max-width:100%}.markdown-body hr{border:none;border-top:1px solid #ddd;margin-top:32px;margin-bottom:32px}.markdown-body code{word-break:break-word;border-radius:2px;overflow-x:auto;background-color:#fff5f5;color:#ff502c;font-size:.87em;padding:.065em .4em}.markdown-body code,.markdown-body pre{font-family:Menlo,Monaco,Consolas,Courier New,monospace}.markdown-body pre{overflow:auto;position:relative;line-height:1.75}.markdown-body pre>code{font-size:12px;padding:15px 12px;margin:0;word-break:normal;display:block;overflow-x:auto;color:#333;background:#f8f8f8}.markdown-body a{text-decoration:none;color:#0269c8;border-bottom:1px solid #d1e9ff}.markdown-body a:active,.markdown-body a:hover{color:#275b8c}.markdown-body table{display:inline-block!important;font-size:12px;width:auto;max-width:100%;overflow:auto;border:1px solid #f6f6f6}.markdown-body thead{background:#f6f6f6;color:#000;text-align:left}.markdown-body tr:nth-child(2n){background-color:#fcfcfc}.markdown-body td,.markdown-body th{padding:12px 7px;line-height:24px}.markdown-body td{min-width:120px}.markdown-body blockquote{color:#666;padding:1px 23px;margin:22px 0;border-left:4px solid #cbcbcb;background-color:#f8f8f8}.markdown-body blockquote:after{display:block;content:""}.markdown-body blockquote>p{margin:10px 0}.markdown-body ol,.markdown-body ul{padding-left:28px}.markdown-body ol li,.markdown-body ul li{margin-bottom:0;list-style:inherit}.markdown-body ol li .task-list-item,.markdown-body ul li .task-list-item{list-style:none}.markdown-body ol li .task-list-item ol,.markdown-body ol li .task-list-item ul,.markdown-body ul li .task-list-item ol,.markdown-body ul li .task-list-item ul{margin-top:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-top:3px}.markdown-body ol li{padding-left:6px}.markdown-body .contains-task-list{padding-left:0}.markdown-body .task-list-item{list-style:none}@media (max-width:720px){.markdown-body h1{font-size:24px}.markdown-body h2{font-size:20px}.markdown-body h3{font-size:18px}}</style><style data-highlight="" data-highlight-key="juejin">.markdown-body pre,.markdown-body pre>code.hljs{color:#333;background:#f8f8f8}.hljs-comment,.hljs-quote{color:#998;font-style:italic}.hljs-keyword,.hljs-selector-tag,.hljs-subst{color:#333;font-weight:700}.hljs-literal,.hljs-number,.hljs-tag .hljs-attr,.hljs-template-variable,.hljs-variable{color:teal}.hljs-doctag,.hljs-string{color:#d14}.hljs-section,.hljs-selector-id,.hljs-title{color:#900;font-weight:700}.hljs-subst{font-weight:400}.hljs-class .hljs-title,.hljs-type{color:#458;font-weight:700}.hljs-attribute,.hljs-name,.hljs-tag{color:navy;font-weight:400}.hljs-link,.hljs-regexp{color:#009926}.hljs-bullet,.hljs-symbol{color:#990073}.hljs-built_in,.hljs-builtin-name{color:#0086b3}.hljs-meta{color:#999;font-weight:700}.hljs-deletion{background:#fdd}.hljs-addition{background:#dfd}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}</style>`

  // console.log('开始执行', _text, _id)
  const targetElement = getDom(_id);

  if (targetElement) {
    targetElement.innerHTML = styleStr + parseToPTagsWithBreaks(_text); // 修改内容
    window.scrollTo({
      top: 0,
      behavior: "smooth" // 添加平滑过渡动画
    });
    console.log('修改成功！');
  } else {
    console.error(`未找到 id 为 ${_id} 的元素`);
  }
}


/**
 * 处理文本换行,将文本解析成p标签格式
 * @param {*} text 
 * @returns 
 */
function parseToPTagsWithBreaks(text) {
  return text
    .split('\n')
    .map(line => {
      const content = line.replace(/\n/g, '<br>'); // 保留段落内的换行
      return `<p>${content}</p>`;
    })
    .join('\n');
}


function scrollView(isNext) {

  const targetElement = getDom(domKey);

  const windowHeight = (window.innerHeight-100)* (isNext ? 1 : -1);

  // 获取当前滚动位置
  const currentScroll = window.scrollY


  // 计算目标滚动位置：当前滚动位置 + 窗口高度
  // 这会将当前窗口底部的可见内容滚动到顶部
  const targetScroll = currentScroll + windowHeight;
  console.log('targetElement',windowHeight,currentScroll,targetScroll)
  // 平滑滚动到目标位置
  window.scrollTo({
    top: targetScroll,
    behavior: 'smooth' // 平滑滚动效果
  });
}